#!/user/bin/env python
# -*- coding:utf-8 -*-
#filename:controllers/tfeetjson.py

'''
从数据库获取tfeet数据返回json格式

 获取tfeet数据并组合成json形式返回
            http://tinyfeet.us/i/getfeet/all/11211?postart=0&srckey=2a2286d27ee79ecdf39ee0266e485f578aa39d2fecunrxwy

            http://tinyfeet.us/i/getfeet/self/12122?postart=0&srckey=2a2286d27ee79ecdf39ee0266e485f578aa39d2fecunrxwy
            http://tinyfeet.us/i/getfeet/fav/12122?postart=0&srckey=adsf234asdf234ads2134sadfasdfasdfasfdasfdasd
            参数名    必选    类型及范围                                    说明
            -----    ---    ----------                          ---------------------------------
            type     True   String{all | self | favorite|}      根据type返回“所有的”、“我的”、“收藏的”tfeet。
            postart  True   Int{默认值0}                         最后一条tfeet id
            uid      False  Int                                 如果type=self or favorite, uid参数为必选
            since_id False    Int{默认值0}                         过滤获取比since_id新的tfeet|| postart与since_id只能二选一，若都选择，则只postart生效
            
            返回结果示例：
            {"tfeets":[
                    {
                        "uname" : "__树上__",
                        "uid" : 1202,
                        "aboutme": "美食制造者",
                        "avator" :"http://tp3.sinaimg.cn/1418987422/50/39535/1",
                        "tfeet": 
                        {
                            "tfid" :12232,
                            "text" :"我一直很想来这里，这是 一个宁静的地方，...",
                            "image" :"http://tp.tinyfeet.us/2323423423/1",
                            "datetime" :20110821143553,
                            "comments" :12,
                            "location" :"中国 湖南 凤凰城",
                            "long" : 1212.2234,
                            "lat" :34.5232,
                            "like" :132,
                            "dislike" :12,
                            "isfav",0
                         }
                        "sort" : "desc"
                    },
                        "uname" : "__树上__",
                        "uid" : 1202,
                        "aboutme": "美食制造者",
                        "avator" :"http://tp3.sinaimg.cn/1418987422/50/39535/1",
                        "tfeet": 
                        {
                            "tfid" :12232,
                            "text" :"我一直很想来这里，这是 一个宁静的地方，...",
                            "image" :"http://tp.tinyfeet.us/2323423423/1",
                            "datetime" :20110821143553,
                            "comments" :12,
                            "location" :"中国 湖南 凤凰城",
                            "long" : 1212.2234,
                            "lat" :34.5232,
                            "like" :132,
                            "dislike" :12,
                            "isfav",0
                         }
                        "sort" : "desc"
                    }
            ]}
            
Created on 2011-8-25

@author: zc

modify on 2011-09-12  None json--> {}
'''

from dbhandle import mysqldb
from config import sqlmap
from config.settings import NEXTFEET
from config.sqlmap import SQL_IS_IWANT

class tfeet_json():
    __dbo = mysqldb.mysqldb()
    def tfeet_json( self, tfid = 0, uid = 0, type = 'all', since_id = 0 ):
        tfeets = None
        if type == 'all':
            """ All tfeet"""
            if tfid <= 0:
                """ 第一次"""  
                sql_tfeet = sqlmap.SQL_ALL1ST % ( NEXTFEET )
            elif tfid > 0:
                """ 第N次 N>=2"""
                sql_tfeet = sqlmap.SQL_ALLMANY % ( tfid, NEXTFEET )
            elif since_id > 0:
                """ 从旧往新获取tfeet"""
                sql_tfeet = sqlmap.SQL_ALLMANY_OLD2NEW % ( since_id, NEXTFEET )
                
        if type == 'self':
            """ 我的tfeet"""
            if tfid <= 0:
                """ 第一次"""  
                sql_tfeet = sqlmap.SQL_USER1ST % ( uid, NEXTFEET )
            elif tfid > 0:
                """ 第N次 N>=2"""
                sql_tfeet = sqlmap.SQL_USERMANY % ( uid, tfid, NEXTFEET )
            elif since_id > 0:
                """ 从旧往新获取tfeet"""
                sql_tfeet = sqlmap.SQL_USERMANY_OLD2NEW % ( since_id, NEXTFEET )
                                
        if type == 'fav':
            """ 我的收藏"""
            if tfid <= 0:
                """ 第一次"""  
                sql_tfeet = sqlmap.SQL_USER1ST_FAV % ( uid, NEXTFEET )
            elif tfid > 0:
                """ 第N次 N>=2"""
                sql_tfeet = sqlmap.SQL_USERMANY_FAV % ( uid, tfid, NEXTFEET )
            elif since_id > 0:
                """ 从旧往新获取tfeet"""
                sql_tfeet = sqlmap.SQL_USERMANY_FAV_OLD2NEW % ( since_id, NEXTFEET )
                
        if len( sql_tfeet ) > 0: 
            tfeets_res = self.__dbo.query( sql_tfeet )
           
        if tfeets_res:
            tfeets = '{"tfeets":['
            for tf in tfeets_res:
                commentCnt = self.getCommentCnt( tf.tfid )
                like = tf.like if tf.like is not None else 0
                dislike = tf.dislike if tf.dislike is not None else 0
                pic_normal = tf.pic_normal if tf.pic_normal is not None else 'None'
                pic_small = tf.pic_small if tf.pic_small is not None else 'None'
                pic_original = tf.pic_original if tf.pic_original is not None else 'None'
                isfav = 0
                tfeets = tfeets + ( '''{
                                    "uname" : "''' + tf.uname + '''",
                                    "uid"   : "''' + str( tf.uid ) + '''",
                                    "aboutme": "''' + tf.description + '''",
                                    "avator" :"''' + tf.profile_image_url + '''",
                                    "tfeet":
                                    {
                                        "tfid"  :"''' + str( tf.tfid ) + '''",
                                        "text"  :"''' + tf.text.replace( '\n', '' ).replace( '\r', '' ) + '''",
                                        "pic_normal" :"''' + pic_normal + '''",
                                        "pic_small" :"''' + pic_small + '''",
                                        "pic_original" :"''' + pic_original + '''",
                                        "datetime" :"''' + str( tf.date ) + '''",
                                        "comments" :"''' + str( commentCnt ) + '''",
                                        "location" :"''' + tf.location + '''",
                                        "long" : "''' + str( tf.longitude ) + '''",
                                        "lat"  :"''' + str( tf.latigude ) + '''",
                                        "like" :"''' + str( like ) + '''",
                                        "dislike" :"''' + str( dislike ) + '''",
                                        "isfav":"''' + str( self.isfav( uid, tf.tfid ) ) + '''"
                                        },
                                    "sort" : "desc"
                            },''' )
            tfeets = tfeets[:-1] #去掉最后一个逗号
            tfeets = tfeets + "]}"
        else:
            tfeets = '{"msg":"208", "errmsg":"没有tfeet记录."}'
        
        if tfeets is None:
            tfeets = '{"msg":"208", "errmsg":"没有tfeet记录."}'
            
        return tfeets
    
    
    def getCommentCnt( self, tfid ):
        """ 根据tfid获取该tfeet评论数 """
        sql_commentcount = sqlmap.SQL_GETCOMMENTSNUM % ( tfid )
        cres = self.__dbo.query( sql_commentcount )
        if cres:
            for tff in cres:
                commentcnt = tff.cnt
        else:
            commentcnt = 0
            
        return commentcnt


    def isfav( self, ai_uid, ai_tfid ):
        """ 判断当前用户是否收藏该tfeet
        参数：uid, tfid
        收藏：1
        未收藏：0
        """
        sql = SQL_IS_IWANT % ( ai_uid, ai_tfid )
        cres = self.__dbo.query( sql )
        if cres:
            isfav = cres[0].isfav
        return isfav
        

if __name__ == "__main__":
    """ 测试 """
    t = tfeet_json()
    s = t.tfeet_json( uid = 1418285287 )
    print s
    
